﻿using SqlSugar;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
namespace EquipmentManagement.ApiHost
{


    public class ExportService
    {
        private readonly ISqlSugarClient _db;
        /// <summary>
        /// 通用Excel导出方法
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="query">查询条件</param>
        /// <param name="fileName">导出文件名</param>
        /// <param name="sheetName">工作表名</param>
        /// <returns>文件流</returns>
        public MemoryStream ExportToExcel<T>(
         List<T> data,
         Dictionary<string, string> columnMappings = null,
         string sheetName = "Sheet1")
        {
            var workbook = new HSSFWorkbook();
            var sheet = workbook.CreateSheet(sheetName);

            // 获取要导出的属性（过滤掉未映射的列）
            var properties = typeof(T).GetProperties()
                .Where(p => columnMappings == null || columnMappings.ContainsKey(p.Name))
                .ToArray();

            // 创建表头
            var headerRow = sheet.CreateRow(0);
            for (int i = 0; i < properties.Length; i++)
            {
                var propName = properties[i].Name;
                var displayName = columnMappings?.GetValueOrDefault(propName) ?? propName;
                headerRow.CreateCell(i).SetCellValue(displayName);
            }

            // 填充数据
            for (int i = 0; i < data.Count; i++)
            {
                var row = sheet.CreateRow(i + 1);
                for (int j = 0; j < properties.Length; j++)
                {
                    var value = properties[j].GetValue(data[i])?.ToString() ?? "";
                    row.CreateCell(j).SetCellValue(value);
                }
            }

            // 自动调整列宽
            for (int i = 0; i < properties.Length; i++)
            {
                sheet.AutoSizeColumn(i);
            }

            var memoryStream = new MemoryStream();
            workbook.Write(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return memoryStream;
        }
    }
}
